package heman.server.controllers;

import heman.server.entities.PlayerManager;
import heman.server.entities.Table;
import heman.server.entities.TableManager;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;

import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.server.interfaces.IProcessServerMessage;

/**
 * ConfirmResponse controller handles ConfirmResponse message.
 * <xs:element name="confirmResponse">
 * 	<xs:complexType>
 * 		<xs:attribute name="table" type="table-id" use="required" /> 
 * 		<xs:attribute name="player" type="valid-player-id" use="required" /> 
 * 	</xs:complexType>
 * </xs:element>
 *
 * @author Yanyi Zhang
 *
 */
public class ConfirmResponseController implements IProcessServerMessage {
	@Override
	public boolean process(Communicator com, Message m){
		String originator = m.getOriginator();
		boolean success = m.success;
		NamedNodeMap map = m.contents().getAttributes();
		String tableID = map.getNamedItem("table").getNodeValue();
		String TargetPlayer = map.getNamedItem("player").getNodeValue();
		Table TargetTable = TableManager.getInstance().getTable(tableID);
		if(TargetTable.getPlayerIDs().size()>3) return false;
		Message r;
		StringBuilder sb = new StringBuilder(Message.responseHeader(true,m.id));
		if(success){
			TargetTable.addPlayer(PlayerManager.getInstance().getPlayer(TargetPlayer));
	        sb.append("<tableResponse>");
	        sb.append(TargetTable.toXML());
	        sb.append("</tableResponse></response>");
	        Document d = Message.construct(sb.toString());
	        r = new Message (d);
	        r.setOriginator(originator);
	        r.setRecipient(originator);//respond to originator
	        r.setBroadcast();//respond to others
	        return com.distribute(r);
		}
		else{
			sb.append("<rejectResponse table=\"");
			sb.append(tableID);
			sb.append("\" player=\"");
			sb.append(TargetPlayer);
			sb.append("\"/></response>");
			Document d = Message.construct(sb.toString());
	        r = new Message (d);
	        r.setOriginator(originator);
	        r.setRecipient(TargetPlayer);//respond to originator
	        return com.distribute(r);
		}
	}
}
